//
//  LYMusicPlayerViewController.m
//  MusicMV
//
//  Created by dllo on 16/3/19.
//  Copyright © 2016年 Eternity. All rights reserved.
//

#import "LYMusicPlayerViewController.h"
#import "LYDayMusicModel.h"



@interface LYMusicPlayerViewController ()

@property (nonatomic, retain) UIImageView *backImageView;/**< 背景图片 */
@property (nonatomic , strong) UIVisualEffectView *visualEfView; /**< 毛玻璃 */
@property (nonatomic, retain) UIImageView *imgView;/**< 音乐图片 */
@property (nonatomic, assign) BOOL isPlay; /**< 判断是否旋转 */
@property (nonatomic, retain) UIImageView *img; /**< 播放的图片 */

@property (nonatomic, retain) UILabel *MusicCurrentTimer; /**< 歌曲当前时间 */
@property (nonatomic, retain) UILabel *MusicAllTimer; /**< 歌曲总时间 */

@property (nonatomic, retain) UISlider *timeSlder; /**< 时间的滑竿 */
@property (nonatomic, retain) UIButton *likeButton; /**< 喜欢的按钮 */
@property (nonatomic, retain) UIButton *upButton; /**< 上一首按钮 */
@property (nonatomic, retain) UIButton *downButton; /**< 下一首按钮 */

@property (nonatomic, retain) NSString *url;/**< 音乐的网址 */
@property (nonatomic, retain) NSString *photo; /**< 图片的网址 */
@property (nonatomic, retain) NSString *name;/**< 作者的名字 */
@property (nonatomic, retain) NSString *sName; /**< 歌曲的名字 */
@property (nonatomic, assign) BOOL isPage; /**< 判断是回到第几页 */
@property (nonatomic, assign) NSInteger index; /**< 记录播放的下标 */

@property (nonatomic, retain) LSPaoMaView *paoMaview;/**< 跑马 */
@property (nonatomic, retain) UILabel *singerLabel; /**< 歌手的名字 */





@end

@implementation LYMusicPlayerViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.backImageView = [[UIImageView alloc] initWithFrame:self.view.frame];
    [_backImageView sd_setImageWithURL:[NSURL URLWithString:_photo]];
    
    _backImageView.userInteractionEnabled = YES;
    
    // 毛玻璃
    self.visualEfView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    _visualEfView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    _visualEfView.alpha = 1;
    _visualEfView.userInteractionEnabled = YES;
    
    UIView *backView = [[UIView alloc] initWithFrame:self.view.frame];
    backView.backgroundColor = [UIColor blackColor];
    backView.alpha = 0.4;
    [_backImageView addSubview:backView];
    [_backImageView addSubview:_visualEfView];
    [self.view addSubview:_backImageView];
    
    // 返回的button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backImageView addSubview:button];
    button.frame = CGRectMake(5 * wt, 15 * ht, 25 * wt, 25 * wt);
    [button setBackgroundImage:[UIImage imageNamed:@"goBack"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

    
    [self createImageView];
    [self createView];
    [self paoView:_name];
    _isPlay = YES;
    
    
}


#pragma mark - set方法重写  赋值
// 第一页的数据
- (void)setMusicArr:(NSMutableArray *)arr index:(NSInteger)index {
    LYMusicModel *model = arr[index];
    self.photo = model.photo;
    self.url = model.origin_stream;
    self.name = model.name;
    self.sName = model.singer;
    self.index = index;
    [self playMusic];
    _isPage = YES;
    
}


// 音乐播放
- (void)playMusic {
    

    [LY_sharePlayeMusicHelp playMusicMp3Url:_url];
    
    
    _img.image = [UIImage imageNamed:@"iconfont-bofangqizanting"];
    
    //   // 0.1秒回调
    LY_sharePlayeMusicHelp.playTimerBlock = ^(CGFloat timer){
        
        //播放时间
        self.MusicCurrentTimer.text = [self timeToString:timer]; //调用方法，赋值
        //总时间
        self.MusicAllTimer.text = [self timeToString:LY_sharePlayeMusicHelp.sumtime - timer];
        [self playTimer:timer]; //调用方法
        
    };
    
    LY_sharePlayeMusicHelp.playToEndBlock = ^(){
        NSLog(@"播放完我单例的观察者会观察到 就会调用block 走这个方法, 播放完在这里做你想做的");
        
        _img.image = [UIImage imageNamed:@"iconfont-bofanganniu"];
        
            _index++;
            
            if (_index < _musicArr.count) {
                
                LYMusicModel *model = _musicArr[_index];
                
                [self change:model];
                
            }else {
                
                _img.image = [UIImage imageNamed:@"iconfont-bofanganniu"];
                [self imgViewStop];
                _isPlay = NO;
        }
        
    };

    
    
}
// 创建歌曲图片
- (void)createImageView {
    
    self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake((WIDTH - 280 * wt) / 2, (HEIGHT / 3 * 2 - 280 * wt) / 2, 280 * wt, 280 * wt)];
    [self.view addSubview:_imgView];
    // 专辑图片
    [self.imgView sd_setImageWithURL:[NSURL URLWithString:_photo]];
    // 设置圆角
    self.imgView.layer.cornerRadius = 280 * wt / 2.0;
    // 裁掉边框
    self.imgView.layer.masksToBounds = YES;
    
    //加边框
    self.imgView.layer.borderWidth = 3;
    self.imgView.layer.borderColor = [UIColor cyanColor].CGColor;
    
    _imgView.userInteractionEnabled = YES;
    
    
    
    [self performSelector:@selector(startAnimate) withObject:self afterDelay:0.1];
    

    
}

// 动画
-(void)startAnimate{
    
    //CALyer动画 core Animation 核心动画(transform.rotation.z沿着z轴旋转,可以自己改下x, 或y 看看效果)animationWithKeyPath根据什么进行动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //旋转的起始值
    animation.fromValue = [NSNumber numberWithFloat:0];
    //旋转的结束值(M_PI 为: 180度)
    animation.toValue = [NSNumber numberWithFloat:M_PI * 2];
    //重复次数(NSIntegerMax最大数,无限了.)
    animation.repeatCount = NSIntegerMax;
    //是否自动回到原来位置
    //    animation.autoreverses = NO;
    //是否按照结束位置继续旋转
    //    animation.cumulative = YES;
    //动画时长
    animation.duration = 20;
    [self.imgView.layer addAnimation:animation forKey:@"动画标记"];
    


}

// 跑马的方法
- (void)paoView:(NSString *)title {
    
    // 文字的大小, 描述文字大小的信息
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17], NSFontAttributeName, nil];
    // 通过文字大小获取文本的高度
    CGRect rect = [title boundingRectWithSize:CGSizeMake(0, HEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    // 跑马放置歌名
    self.paoMaview = [[LSPaoMaView alloc] initWithFrame:CGRectMake((WIDTH - rect.size.width) / 2, 30 * ht, rect.size.width, 40 * ht) title:[NSString stringWithFormat:@"      %@      ", title] BackColor:nil textColor:[UIColor whiteColor] textFont:15];
    [self.view addSubview:_paoMaview];
    
}

// 页面铺设
- (void)createView {
    
    // 播放的图标
    self.img = [[UIImageView alloc] initWithFrame:CGRectMake((_imgView.frame.size.width - 40 * wt) / 2, (_imgView.frame.size.height - 40 * wt) / 2, 40 * wt, 40 * wt)];
    _img.image = [UIImage imageNamed:@"iconfont-bofangqizanting"];
    _img.center = _imgView.center;
    [self.view addSubview:_img];
    
    // 给img添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_img addGestureRecognizer:tap];
    
   _img.userInteractionEnabled = YES;

    
    
    // 滑竿
    self.timeSlder = [[UISlider alloc] initWithFrame:CGRectMake(60 * wt, _imgView.frame.size.height + _imgView.frame.origin.y + 40 * ht, WIDTH - 120 * wt, 20 * ht)];
    [self.visualEfView addSubview:_timeSlder];
    [_timeSlder addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];

    // 文字的大小, 描述文字大小的信息
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17], NSFontAttributeName, nil];
    // 歌手的名字
    CGRect rect1 = [_sName boundingRectWithSize:CGSizeMake(0, HEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    self.singerLabel = [[UILabel alloc] initWithFrame:CGRectMake((WIDTH - rect1.size.width - 120 * wt) / 2, _timeSlder.frame.size.height + _timeSlder.frame.origin.y + 10 * ht, rect1.size.width + 200 * wt, 40 * ht)];
    [self.view addSubview:_singerLabel];
    _singerLabel.text = [NSString stringWithFormat:@"作者 : %@", _sName];
    _singerLabel.textColor = [UIColor whiteColor];
    
    
    //歌曲当前时间
    self.MusicCurrentTimer = [[UILabel alloc] initWithFrame:CGRectMake(5 * wt, _imgView.frame.size.height + _imgView.frame.origin.y + 30 * ht, 50 * wt, 40 * ht)];
    [self.visualEfView addSubview:self.MusicCurrentTimer];
    self.MusicCurrentTimer.textColor = [UIColor grayColor];
    self.MusicCurrentTimer.text = @"00:00";
    self.MusicCurrentTimer.font = [UIFont systemFontOfSize:17];
    
    //歌曲总时间
    self.MusicAllTimer = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH - 55 * wt, _imgView.frame.size.height + _imgView.frame.origin.y + 30 * ht, 50 * wt, 40 * ht)];
    [self.visualEfView addSubview:self.MusicAllTimer];
    self.MusicAllTimer.textColor = [UIColor grayColor];
    self.MusicAllTimer.text = @"00:00";
    self.MusicAllTimer.font = [UIFont systemFontOfSize:17];
    
    // 喜欢按钮
    self.likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.visualEfView addSubview:_likeButton];
    _likeButton.frame = CGRectMake((WIDTH - 40 * wt) / 2, _singerLabel.frame.size.height + _singerLabel.frame.origin.y + 25 * ht, 40 * wt, 40 * wt);
    [_likeButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucangshi"] forState:UIControlStateNormal];
    
    //上一首按钮
    self.upButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.visualEfView addSubview:_upButton];
    _upButton.frame = CGRectMake((WIDTH / 2 - 20 * wt - 40 * wt) / 2, _singerLabel.frame.size.height + _singerLabel.frame.origin.y + 25 * ht, 40 * wt, 40 * wt);
    [_upButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shangyishou"] forState:UIControlStateNormal];
    [_upButton addTarget:self action:@selector(upAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 下一首按钮
    self.downButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.visualEfView addSubview:_downButton];
    _downButton.frame = CGRectMake((WIDTH / 2 + 20 * wt + ((WIDTH - (WIDTH / 2 + 20 * wt)) - 40 * wt) / 2), _singerLabel.frame.size.height + _singerLabel.frame.origin.y + 25 * ht, 40 * wt, 40 * wt);
    [_downButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xiayishou"] forState:UIControlStateNormal];
    [_downButton addTarget:self action:@selector(downAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

// 图片停止转
- (void)imgViewStop {
    
    CFTimeInterval stopTime = [self.imgView.layer convertTime:CACurrentMediaTime() fromLayer:nil];//CACurrentMediaTime()绝对时间,也就是持续 时间,一直走.
    //设置动画速度
    self.imgView.layer.speed = 0;
    //保存时间的偏移量
    self.imgView.layer.timeOffset = stopTime;
    
}

// 图片开始转
- (void)imgViewStart {
    
    //速度设置为1
    self.imgView.layer.speed = 1;
    self.imgView.layer.beginTime = 0; //把原来的,上次的开始时间清零
    
    //找到时间偏移量
    CFTimeInterval stopTime = self.imgView.layer.timeOffset;
    //设置开始的时间
    self.imgView.layer.beginTime = [self.imgView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
}


// 要暂停和开始
- (void)tapAction:(UITapGestureRecognizer *)tap {
    
    if (_isPlay) {
        
        [self imgViewStop];
        
        _img.image = [UIImage imageNamed:@"iconfont-bofanganniu"];
        
        [LY_sharePlayeMusicHelp pause];
        
    }else {
        
        [self imgViewStart];
        
        [LY_sharePlayeMusicHelp seekToTime:_timeSlder.value];
        
        _img.image = [UIImage imageNamed:@"iconfont-bofangqizanting"];
        
        [self imgViewStop];
        
    }
   
    _isPlay = !_isPlay;
}


//0.1秒block回调的方法
- (void)playTimer:(CGFloat)timer{
    [self imgViewStop];
    self.timeSlder.value = timer / LY_sharePlayeMusicHelp.sumtime; //给滑竿赋值
    [self imgViewStart];
}

- (void)sliderAction:(UISlider *)slider {
    
    
    [LY_sharePlayeMusicHelp seekToTime:slider.value];
    
}

#pragma mark 获取字符串时间
- (NSString *)timeToString:(CGFloat)time{
    
    NSInteger minutes = (NSInteger)time / 60; //分钟
    NSInteger seconds = (NSInteger)time % 60; //秒
    //转换为string
    NSString *string = [NSString stringWithFormat:@"%02ld:%02ld",minutes,seconds];
    
    return string;
}

#pragma mark - button 点击方法
- (void)buttonAction:(UIButton *)button {
    
    
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        
        self.imgView.transform = CGAffineTransformIdentity;
        [LY_sharePlayeMusicHelp pause];
    
    
}

/** 上一曲点击 */
- (void)upAction:(UIButton *)button {
   
    _index--;
    
    if (_index < 0) {
        
        _index = _musicArr.count - 1;
        LYMusicModel *model = _musicArr[_index];
        
        [self change:model];

    }else {
        
        LYMusicModel *model = _musicArr[_index];
        
        [self change:model];
        
    }
    
    
}

/** 下一曲点击 */
- (void)downAction:(UIButton *)button {
    
           
        _index++;
    
        // 判断下标
        if (_index < _musicArr.count) {
            LYMusicModel *model = _musicArr[_index];
            
            [self change:model];
            
            // 音乐没有了
        }else {
            _index = 0;
            
            LYMusicModel *model = _musicArr[_index];
            
            [self change:model];
            
        
    }

    
}

// 当音乐发生变化的时候
- (void)change:(LYMusicModel *)model {
    
    [LY_sharePlayeMusicHelp playMusicMp3Url:model.origin_stream];
    // 专辑图片
    [self.imgView sd_setImageWithURL:[NSURL URLWithString:model.avatar]];
    _singerLabel.text = [NSString stringWithFormat:@"作者 : %@", model.singer];
    [self.paoMaview setHidden:YES];
    [self paoView:model.name];
    
    _img.image = [UIImage imageNamed:@"iconfont-bofangqizanting"];
    [self imgViewStart];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
